<template>
    <div class="app-container">
        <!-- 工具栏：标题和按钮在同一行 -->
        <div class="toolbar">
            <div style="width:60% ;margin-left: 20%;">
                <h1 class="toolbar-title">耕地地力资金请示文件(乡级)</h1>
            </div>


            <div class="button-group">
                <!-- 左侧按钮 -->
                <button type="button" class="btn-primary" :loading="buttonLoading" @click="handleStamp()">电子印章</button>
                <button type="button" class="btn-primary" @click="submitTownSub()">提交</button>

                <!-- 右侧按钮组（自动推到右边） -->
                <div class="right-buttons">
                    <button type="button" class="btn-primary" @click="handleExportPdf()">导出PDF</button>
                    <button type="button" class="btn-primary"
                        @click="handleExportExcel('table.xlsx', '#tableId')">导出附表</button>
                    <button type="button" class="btn-primary" @click="handlePreview()">预览</button>
                </div>
            </div>
            <div style="width: 60%;height: 150px;margin-left: 20%;">
                <el-form ref="elForm" :model="form" :rules="rules" size="medium" label-width="100px" label-position="left">
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="红头标题" prop="redTitle">
                                <el-input v-model="form.redTitle" placeholder="红头标题" clearable
                                    :style="{ width: '100%' }"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="文号" prop="redCode">
                                <el-input v-model="form.redCode" placeholder="请输入文号" clearable
                                    :style="{ width: '100%' }"></el-input>
                            </el-form-item>
                        </el-col>

                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="申请人类型" prop="personType">
                                <el-select v-model="form.personType" placeholder="申请人类型" clearable
                                    :style="{ width: '100%' }">
                                    <el-option v-for='item in personTypes' :label="item.label" :key="item.value"
                                        :value="item.value"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="申报单位" prop="enterprise">
                                <el-input v-model="form.enterprise" placeholder="申报单位" clearable
                                    :style="{ width: '100%' }"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="24">
                        <el-col :span="24">
                            <el-form-item label="下发文件" prop="dadouNotice">
                                <el-input v-model="form.dadouNotice" placeholder="请输入文件名" type="textarea"
                                    :autosize="{ minRows: 1, maxRows: 4 }" clearable :style="{ width: '100%' }"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>

                </el-form>
            </div>
        </div>

        <!-- PDF 内容区域 -->
        <div class="pdfDom" id="pdfDom">
            <!-- 红头部分 -->
            <div class="red-header">
                <h1 class="red-title">{{ form.redTitle }}</h1>
            </div>

            <!-- 文号 -->


            <!-- 红线与五角星 -->
            <!-- <el-divider><i class="el-icon-star-on"></i></el-divider> -->
            <div class="separator">
                <div class="red-line"></div>
                <!-- <div class="star">★</div> -->
                <div class="red-line1"></div>
            </div>
            <div class="doc-number">
                {{ form.redCode }}
            </div>

            <!-- 标题 -->
            <p class="title">关于{{ townName }}{{ year }}年耕地地力补贴资金的函</p>


            <!-- 主送机关：顶格 -->
            <p class="addressee">区农业农村局：</p>

            <!-- 正文：首行缩进 -->
            <p class="content">
                根据{{ form.dadouNotice }}文件要求，{{ year }}年耕地力保护每亩补贴标准{{ prcieForm.farmland }}元。我{{ form.personType }}{{ year
                }}年耕地力保护面积{{ sumData.farmlandbyxitotal }}亩，耕地力保护补贴金额为{{ sumData.farmlandbyxitotalPri }}元。
            </p>
            <p class="content">现特申请地力补贴资金。</p>
            <p class="content">特此申请</p>
            <p class="content">附件：耕地地力补贴明细</p>

            <!-- 发文机关和日期 -->
            <div class="footer" style="margin-top: 200px;">
                <p>{{ form.enterprise }}</p>
                <p>{{ year }}年{{ month }}月{{ day }}日</p>
            </div>
        </div>

        <div class="pdfDom1" id="pdfHengDom">
            <p class="title" style="font-size: 22px;"> {{ townName }}{{ year }} 年耕地地力补贴面积数据汇总表</p>
            <el-row style="text-align: center;font-size: 20px;">
                <el-col :span="12">制表人：{{ userName }}</el-col>
                <!-- <el-col :span="12">单位：亩</el-col> -->
            </el-row>
            <el-table :data="tableData" style="width: 100%" fit border show-summary id="tableId">
                <el-table-column label="单位名称" align="center" prop="villageName" />
                <el-table-column label="耕地地力补贴面积" align="center" prop="farmlandareaAmount" />
                <el-table-column label="耕地地力补贴金额" align="center" prop="farmlandareaAmountPri" />
            </el-table>
        </div>

    </div>
</template>
    
<script>
import { listProduce, savePrice, getPrice, submitProduce, queryGroupData, submitSub, queryTownRes } from "@/api/agriculture/agriculture";
import { stamp } from "@/api/agriculture/file";
import * as XLSX from 'xlsx';
import FileSaver from 'file-saver'
// import * as pdfjsLib from 'pdfjs-dist';
// import * as pdfjsLib from 'pdfjs-dist/legacy/build/pdf';
export default {
    name: "TownFarmSub",
    data() {
        const now = new Date();
        return {
            townName: '',
            userName: '',
            role: '',
            straName: '滴道区',
            year: now.getFullYear(),
            month: String(now.getMonth() + 1),
            day: String(now.getDate()),
            htmlTitle: '',
            //进度条
            buttonLoading: false,
            uploadLoading: null, // 用于保存 loading 实例
            progressText: '正在准备盖章文件...',

            //控制是否下载
            isDownload: false, //否为不下载
            queryTownSubUrl: '',//查询到的自己提交资金请示文件

            filePdf: undefined,  //生成的PDF blob
            fileExcel: undefined,
            mergedFile: undefined, //合并的blob File

            filePdfUrl: undefined,   //电子印章返回的url
            fileExcelUrl: undefined,
            mergedUrl: undefined, //合并后盖章后返回的url


            tableData: [],
            prcieForm: {
                yumi: undefined,
                dadou: undefined,
                // daogu: undefined,
                daogudibiao: undefined,
                daogudixia: undefined,
                gaodanbaidadou: undefined,
                gaoyoudadou: undefined,
                farmland: undefined
            },
            sumData: [],

            queryParams: {
                townName: undefined,
                appType: '耕地地力补贴',
                isprice: '2',
                year: now.getFullYear(),
                pageNum: 1,
                pageSize: 10
            },
            form: {
                redTitle: '文件',
                redCode: '〔2025〕号',//机关代字
                personType: '乡',//申请区域的类型，我乡，我农场，我区
                enterprise: '人民政府',
                dadouNotice: '鸡财指(农)(2025)68号', //下发的文件全称
            },
            rules: {
                redTitle: [{
                    required: true,
                    message: '请输入红头文件名',
                    trigger: 'blur'
                }],
                personType: [{
                    required: true,
                    message: '请选择申请方类型',
                    trigger: 'change'
                }],
                enterprise: [{
                    required: true,
                    message: '请输入申报单位',
                    trigger: 'blur'
                }],
            },

            personTypes: [{
                "label": "乡",
                "value": "乡"
            },
            {
                "label": "镇",
                "value": "镇"
            },
            {
                "label": "林场",
                "value": "林场"
            },
            {
                "label": "农场",
                "value": "农场"
            },
            {
                "label": "公司",
                "value": "公司"
            }]
        };
    },
    created() {
        // console.log("目前登录的角色是", this.$store.state.user.name, this.$store.state.user.roles[0])
        console.log("目前登录的角色是", this.$store.state.user.user.userName, this.$store.state.user.roles[0])
        this.userName = this.$store.state.user.user.userName;
        this.townName = this.$store.state.user.user.townName;
        this.role = this.$store.state.user.roles[0];
        this.htmlTitle = this.townName + '耕地地力资金请示文件';
        this.queryParams.townName = this.townName;

    },
    mounted() {
        this.fetchPriceData();
        this.getList();
        this.getGroupList();
    },

    methods: {

        async handlePreview() {
            await queryTownRes({ year: this.year, type: '耕地地力补贴', name: this.townName, isprice: '2' }).then(res => {
                if (res.rows.length > 0 && res.rows[res.rows.length - 1].hechafile) {
                    // console.log("res", res.rows[res.rows.length - 1].hechafile)
                    this.queryTownSubUrl = res.rows[res.rows.length - 1].hechafile.replace('172.24.254.135', '111.40.188.220');
                    // console.log("res2", this.queryTownSubUrl)
                }
            })

            if (this.queryTownSubUrl) {
                this.$modal.msgSuccess("打开已提交的请示文件");
                // this.$router.push({ name: 'PdfViewer', query: { url: this.queryTownSubUrl } })
                const routeData = this.$router.resolve({
                    name: 'PdfViewer',
                    query: { url: this.queryTownSubUrl }
                });
                window.open(routeData.href, '_blank');

            }
            else if (this.mergedUrl) {
                this.$modal.msgSuccess("打开已盖章的请示文件");
                // this.$router.push({ name: 'PdfViewer', query: { url: this.getProxyUrl(this.filePdfUrl) } })
                const routeData = this.$router.resolve({
                    name: 'PdfViewer',
                    query: { url: this.getProxyUrl(this.mergedUrl) }
                });
                window.open(routeData.href, '_blank');

            } else {
                this.$message({
                    message: '还未进行盖章',
                    type: 'warning'
                });
            }
        },
        //替换
        getProxyUrl(originalUrl) {
            return originalUrl.replace(/^(https?):\/\/172\.24\.254\.135/, '$1://111.40.188.220');
        },
        async handleStamp() {
            this.buttonLoading = true;

            // 显示全局 loading，带进度文字
            this.uploadLoading = this.$loading({
                lock: true,
                text: this.progressText,
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)',
            });

            try {
                // --- 步骤1：生成 PDF ---
                this.progressText = '正在生成 PDF 文件...';
                this.uploadLoading.text = this.progressText;
                await this.handlePdf(false);
                await this.handleExcel(false);

                if (!this.filePdf) {
                    this.$modal.msgError("PDF1 生成失败");
                    return;
                }
                if (!this.fileExcel) {
                    this.$modal.msgError("PDF2 生成失败");
                    return;
                }
                console.log("生成的pdf Blob", this.filePdf)
                console.log("生成的excel Blob", this.fileExcel)
                // 合并两个blob
                await this.mergePdfBlobs(this.filePdf, this.fileExcel);
                console.log("合并的File Blob", this.mergedFile)



                // --- 步骤2：上传并盖章（耗时操作）---
                this.progressText = '正在上传并盖章，请耐心等待...';
                this.uploadLoading.text = this.progressText;
                const formData = new FormData();
                formData.append("file", this.mergedFile);
                formData.append("signArea", '2');
                const res = await stamp(formData); // 假设这个接口很慢

                this.mergedUrl = res.msg;
                console.log("合并后盖章的pdf", this.mergedUrl);
                // const formData1 = new FormData();
                // formData1.append("file", this.filePdf);
                // const res1 = await stamp(formData1); // 假设这个接口很慢
                // const formData2 = new FormData();
                // formData2.append("file", this.fileExcel);
                // const res2 = await stamp(formData2); // 假设这个接口很慢
                // // --- 成功 ---
                // this.filePdfUrl = res1.msg;
                // this.fileExcelUrl = res2.msg;

                // console.log("盖章的pdf", this.filePdfUrl);
                // console.log("盖章的excel", this.fileExcelUrl);

                this.$modal.msgSuccess("盖章成功");

            } catch (error) {
                console.error("盖章失败", error);
                this.$modal.msgError("操作失败：" + (error.message || "未知错误"));
            } finally {
                // 关闭 loading
                if (this.uploadLoading) {
                    this.uploadLoading.close();
                }
                this.uploadLoading = null;
                this.buttonLoading = false;
                this.progressText = '正在准备盖章文件...'; // 重置
            }
        },

        getList() {
            this.tableLoading = true;
            console.log("查询表单", this.queryParams);
            listProduce(this.queryParams).then(response => {

                this.total = response.total; // 总条数
                this.sumData = response;
                console.log("统计字段", this.sumData);
            });
        },
        async handleExcel(value) {
            try {
                const pdfBlob = await this.getHengPdf({ download: value });
                // console.log("excelBlob", pdfBlob);
                this.fileExcel = new File([pdfBlob], '乡级核查函附件.pdf', {
                    type: 'pdf',
                    lastModified: Date.now()
                });
                // console.log("fileExcel", this.fileExcel)
            } catch (error) {
                console.error("生成 PDF 失败", error);
            }
        },
        getGroupList() {
            this.tableLoading = true;
            const queryTab = { year: this.year, appType: '耕地地力补贴', townName: this.townName };
            console.log("queryTab", queryTab);
            queryGroupData(queryTab).then(response => {
                this.tableData = response;
                console.log("分村数据", this.tableData);
                this.tableLoading = false;
            })
        },
        fetchPriceData() {
            getPrice({ year: this.year })
                .then(res => {
                    const data = res || [];
                    console.log("补贴金额", data);

                    const mapping = {
                        '玉米补贴': 'yumi',
                        '大豆补贴': 'dadou',
                        '稻谷地表水补贴': 'daogudibiao',
                        '稻谷地下水补贴': 'daogudixia',
                        '高蛋白大豆补贴': 'gaodanbaidadou',
                        '高油大豆补贴': 'gaoyoudadou',
                        '耕地地力补贴': 'farmland'
                    };

                    data.forEach(item => {
                        const field = mapping[item.type];
                        console.log("补贴字段", field);
                        if (field) {
                            // 填充值（注意：price 可能是字符串）
                            this.prcieForm[field] = Number(item.price);
                        }
                    });
                })
                .catch(err => {
                    this.$message.error('获取补贴数据失败：' + (err.message || '网络错误'));
                    this.initSubmitStates(); // 出错时仍允许编辑
                });
        },
        // 合并两个 PDF Blob，第二个 PDF 的每页将逆时针旋转 90 度
        async mergePdfBlobs(verticalBlob, horizontalBlob) {
            // 1. 加载 pdf-lib
            const { PDFDocument, degrees } = await import('pdf-lib'); // 动态导入，避免打包问题（可选）
            // 或者如果你已经 import 过：import { PDFDocument } from 'pdf-lib';

            // 2. 创建新的 PDF 文档
            const mergedPdf = await PDFDocument.create();

            // 3. 加载两个 Blob 的 ArrayBuffer
            const [verticalBytes, horizontalBytes] = await Promise.all([
                verticalBlob.arrayBuffer(),
                horizontalBlob.arrayBuffer()
            ]);

            const pdf1Doc = await PDFDocument.load(verticalBytes); // 竖向 PDF
            const pdf2Doc = await PDFDocument.load(horizontalBytes); // 横向 PDF

            // 4. 复制竖向 PDF 的所有页面
            const pages1 = await mergedPdf.copyPages(pdf1Doc, pdf1Doc.getPageIndices());
            pages1.forEach(page => mergedPdf.addPage(page));

            // 5. 复制横向 PDF 的所有页面，并逐页旋转
            const pages2 = await mergedPdf.copyPages(pdf2Doc, pdf2Doc.getPageIndices());
            pages2.forEach(page => {
                page.setRotation(degrees(90)); // 逆时针旋转 90 度
                mergedPdf.addPage(page);
            });

            // 6. 导出为 Uint8Array
            const mergedPdfBytes = await mergedPdf.save(); // 返回 Uint8Array

            // 7. 转为 Blob
            // return new Blob([mergedPdfBytes], { type: 'application/pdf' });

            // 6. 转为 Blob
            const mergedBlob = new Blob([mergedPdfBytes], { type: 'application/pdf' });
            this.mergedFile = new File([mergedBlob], '乡级核查函合并.pdf', {
                type: 'pdf',
                lastModified: Date.now()
            });

            // // 7. 创建下载链接
            // const url = URL.createObjectURL(mergedBlob);
            // const a = document.createElement('a');
            // a.href = url;
            // a.download = '合并盖章文件.pdf'; // 下载的文件名
            // a.style.display = 'none';
            // document.body.appendChild(a);
            // a.click();

            // // 8. 清理内存
            // document.body.removeChild(a);
            // URL.revokeObjectURL(url);
            // console.log('合并 PDF 已成功导出！');
        },
        //生成pdf和blob，并控制是否下载
        async handlePdf(value) {
            return new Promise(async (resolve, reject) => {
                // 使用 validate 的回调，但包裹在 Promise 中
                this.$refs['elForm'].validate(async (valid) => {
                    if (valid) {
                        await this.$nextTick(); // 确保 DOM 更新
                        try {
                            const pdfBlob = await this.getPdf({ download: value }); // 这里 await getPdf()
                            console.log("pdfBlob", pdfBlob);

                            this.filePdf = new File([pdfBlob], '乡级耕地地力核查函.pdf', {
                                type: 'pdf',
                                lastModified: Date.now()
                            });
                            resolve(); // ✅ 成功生成文件，resolve
                        } catch (error) {
                            console.error("生成 PDF 失败", error);
                            reject(error);
                        }
                    } else {
                        reject(new Error("表单验证未通过"));
                    }
                });

            });
        },

        //直接导出pdf
        async handleExportPdf() {
            try {
                await this.handlePdf(true);
            } catch (error) {
                console.error("导出PDF失败", error);
                this.$modal.msgError("操作失败：" + (error.message || "未知错误"));
            }

        },
        //附表导出为Excel
        handleExportExcel(name, tableName) {
            let sel = XLSX.utils.table_to_book(document.querySelector(tableName));
            let selIn = XLSX.write(sel, { bookType: 'xlsx', bookSST: true, type: 'array' });
            try {
                FileSaver.saveAs(new Blob([selIn], { type: 'application/octet-stream' }), name);
            } catch (e) {
                if (typeof console !== 'undefined') console.log(e, selIn);
            }
            return selIn;
        },


        submitTownSub() {
            //乡级一键提交
            if (this.mergedUrl) {
                submitSub({ hechafile: this.mergedUrl, year: this.year, appType: '耕地地力补贴', name: this.townName, isprice: "2" }).then(response => {
                    console.log("res", response)
                    this.$modal.msgSuccess("提交成功");

                }).catch(error => {
                    this.$message({ type: 'error', message: '请重新电子盖章并等待!' });
                });
            } else {
                this.$message({ type: 'error', message: '还没有对文件进行电子盖章!' });
            }
        }
    }

};
</script>
    
<style scoped>
.app-container {
    /* width: 60%; */
    align-items: center;
    /* margin-left: 20%; */
    padding: 20px;
    font-family: "SimSun", "宋体", serif;
    color: black;
}

.pdfDom {
    width: 210mm;
    min-height: 297mm;
    margin: 0 auto;
    padding: 30mm 30mm;
    box-sizing: border-box;
    background-color: white !important;
    position: relative;
    /* 必须加 */
    /* 必须加 !important */
    /* box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); */
}

.pdfDom1 {
    min-width: 297mm;
    height: 210mm;
    margin: 0 auto;
    padding: 20mm 20mm;
    box-sizing: border-box;
    background-color: white !important;
    margin-left: 20px;
    font-family: "SimSun", "宋体";
    color: black;
}

.pdfDom1::v-deep .el-table th.gutter {
    display: none;
    width: 0
}

.pdfDom1 ::v-deep.el-table colgroup col[name='gutter'] {
    display: none;
    width: 0;
}

.pdfDom1::v-deep .el-table__body {
    width: 100% !important;
}

.pdfDom1::v-deep .el-table__header {
    width: 100% !important;
}

.pdfDom1::v-deep .el-table__footer {
    width: 100% !important;
}

::v-deep .el-table--border .el-table__cell {
    border-color: black !important;
    padding: 6px 0;
}

.el-table {
    color: #000;
    border: #000 1px solid;
}

::v-deep .el-table__header th {
    color: #000;
    font-size: 16px;
    background-color: #fff;
}

::v-deep .el-table__row {
    color: #000;
    font-size: 18px;
}


::v-deep .el-table__footer-wrapper .el-table__footer td {
    color: #000;
    background-color: #fff;
    font-size: 18px;
}


/* 红头标题 */
.red-header .red-title {
    font-size: 54px;
    /* 约72px视觉效果，但更标准 */
    text-align: center;
    color: red;
    font-weight: 700;
    margin-bottom: 60px;
    letter-spacing: 1px;
    font-family: "SimSun", "宋体";
}

/* 文号 */
.doc-number {
    text-align: right;
    font-size: 20px;
    font-weight: 400;
    /* margin: 10px 0; */
    font-family: "SimSun", "宋体";
}

/* 分隔线 + 五角星 */
.separator {
    /* display: flex; */
    align-items: center;
    justify-content: center;
    /* margin: 20px 0; */
}

.red-line {
    width: 100%;
    height: 4px;
    background-color: rgb(238, 0, 0);
    /* margin: 0 10px; */
}

.red-line1 {
    width: 100%;
    height: 2px;
    background-color: rgb(238, 0, 0);
    margin-top: 2px;
    /* margin: 0 10px; */
}


.star {
    color: rgb(238, 0, 0);
    font-size: 28px;
    font-weight: bold;
}

/* 标题 */
.title {
    text-align: center;
    font-size: 28px;
    font-weight: bold;
    margin-bottom: 20px;
    width: 94%;
    margin-left: 3%;
    line-height: 1.8;
    font-family: "SimSun", "宋体";
    color: #000;
    /* 显式设置黑色 */
}

/* 主送机关：顶格左对齐 */
.addressee {
    text-align: left;
    font-size: 20px;
    line-height: 1.6;
    font-weight: 400;
    text-indent: 0;
    margin: 0;
}

/* 正文段落：首行缩进2字符 */
.content {
    text-indent: 2em;
    font-size: 20px;
    line-height: 1.6;
    /* font-weight: bold; */
    margin: 10px 0;
    text-align: justify;
    font-weight: 400;
    font-family: "SimSun", "宋体";
}

/* 落款（发文机关 + 日期） */
.footer {
    position: absolute;
    bottom: 12%;
    right: 30mm;
    text-align: right;
    font-size: 20px;
    font-weight: 400;
    font-family: "SimSun", "宋体";
}

/* 工具栏：标题和按钮水平排列 */
.toolbar {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 20px;
    /* 按钮之间、标题与按钮之间的间距 */
    margin-bottom: 20px;
    flex-wrap: wrap;
    /* 小屏幕时换行 */
}

.toolbar .toolbar-title {
    margin: 0;
    font-size: 24px;
    color: #333;
    font-weight: bold;
    white-space: nowrap;
}

.button-group {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    /* 左对齐整体内容 */
    gap: 30px;
    width: 60%;
    margin-left: 20%;
    padding: 10px 0;
}

/* 关键：使用 margin-left: auto 将右侧推到最右边 */
.right-buttons {
    margin-left: auto;
    /* 👈 核心：自动占据左侧空白 */
    display: flex;
    gap: 30px;
}

.btn-primary {
    padding: 8px 16px;
    font-size: 14px;
    border: none;
    border-radius: 4px;
    background-color: #007bff;
    color: white;
    cursor: pointer;
    transition: background-color 0.3s;
}

.btn-primary:hover {
    background-color: #0056b3;
}

/* 响应式：小屏幕下工具栏换行 */
@media (max-width: 600px) {
    .toolbar {
        flex-direction: row;
        align-items: flex-start;
    }

    /* .button-group {
      margin-top: 8px;
      margin-right: 8px;
  
    } */
}
</style>